<template>
  <q-layout>
    <q-page-container>
      <q-page class="login-page" :style="backgroundStyle">
        <q-card class="login-card" :class="{ 'login-card--mobile': $q.screen.lt.sm }">
          <!-- 标题区域 -->
          <q-card-section class="login-card__header">
            <h2 class="login-title">用户登录</h2>
          </q-card-section>

          <!-- 表单区域 -->
          <q-card-section class="login-card__body">
            <q-form class="login-form" @submit.prevent="handleLogin">
              <!-- 用户名输入 -->
              <q-input
                filled
                v-model="formState.username"
                label="用户名"
                lazy-rules
                :rules="validationRules.username"
                clearable
                class="login-form__input"
                aria-label="用户名"
              >
                <template v-slot:prepend>
                  <q-icon name="person" />
                </template>
              </q-input>

              <!-- 密码输入 -->
              <q-input
                :type="isPwd ? 'password' : 'text'"
                filled
                v-model="formState.password"
                label="密码"
                lazy-rules
                :rules="validationRules.password"
                class="login-form__input"
                aria-label="密码"
              >
                <template v-slot:prepend>
                  <q-icon name="lock" />
                </template>
                <template v-slot:append>
                  <q-icon
                    :name="isPwd ? 'visibility_off' : 'visibility'"
                    class="cursor-pointer"
                    @click="isPwd = !isPwd"
                    aria-label="切换密码可见性"
                  />
                </template>
              </q-input>

              <!-- 验证码区域 -->
              <div v-if="captchaEnabled" class="login-form__captcha">
                <q-input
                  filled
                  v-model="formState.captcha"
                  label="验证码"
                  lazy-rules
                  :rules="validationRules.captcha"
                  class="login-form__captcha-input"
                  aria-label="验证码"
                >
                  <template v-slot:prepend>
                    <q-icon name="verified" />
                  </template>
                </q-input>
                <img
                  :src="captchaImage"
                  alt="验证码"
                  class="login-form__captcha-image"
                  @click="refreshCaptcha"
                  aria-label="刷新验证码"
                />
              </div>

              <!-- 记住我 & 忘记密码 -->
              <div class="login-form__options">
                <q-checkbox v-model="formState.remember" label="记住我" dense aria-label="记住我" />
                <router-link to="/forgot-password" class="login-form__forgot-password">
                  忘记密码?
                </router-link>
              </div>

              <!-- 登录按钮 -->
              <q-btn
                label="登录"
                type="submit"
                color="primary"
                class="login-form__submit"
                :loading="loading"
                aria-label="登录"
              >
                <template v-slot:loading>
                  <q-spinner-hourglass class="on-left" />
                  登录中...
                </template>
              </q-btn>
            </q-form>

            <!-- 注册链接 -->
            <div class="login-card__footer">
              <span class="login-card__footer-text">还没有账号?</span>
              <router-link to="/register" class="login-card__register-link"> 立即注册 </router-link>
            </div>
          </q-card-section>
        </q-card>
      </q-page>
    </q-page-container>
  </q-layout>
</template>

<script setup>
import { getCodeImg } from '@/api/sys/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import useUserStore from '@/stores/modules/user'
import { ref, computed, onMounted, reactive } from 'vue'
import { useQuasar } from 'quasar'
import { useRouter, useRoute } from 'vue-router'
import loginBackground from '../assets/images/login-background.jpg'
import { throttle } from 'lodash-es'

// 使用Quasar和Router
const $q = useQuasar()
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const formState = reactive({
  username: '',
  password: '',
  captcha: '',
  remember: false,
})

const captchaImage = ref('')
const captchaId = ref('')
// 验证码开关
const captchaEnabled = ref(true)
const isPwd = ref(true)
const loading = ref(false)
const redirect = ref('')

// 背景样式配置
const backgroundConfig = reactive({
  image: loginBackground,
  blur: 3,
  opacity: 0.7,
})

// 验证规则
const validationRules = {
  username: [(val) => !!val || '请输入用户名'],
  password: [(val) => !!val || '请输入密码', (val) => val.length >= 6 || '密码至少6位'],
  captcha: [(val) => !!val || '请输入验证码'],
}

// 计算属性
const backgroundStyle = computed(() => ({
  height: '100vh',
  minHeight: '600px',
  backgroundImage: `linear-gradient(
    rgba(0, 0, 0, ${backgroundConfig.opacity}),
    rgba(0, 0, 0, ${backgroundConfig.opacity})
  ), url(${backgroundConfig.image})`,
  backgroundSize: 'cover',
  backgroundPosition: 'center',
  backgroundRepeat: 'no-repeat',
  backdropFilter: `blur(${backgroundConfig.blur}px)`,
  transition: 'all 0.5s ease',
}))

// Cookie处理
const cookieHandler = {
  get() {
    return {
      username: Cookies.get('username') || '',
      password: Cookies.get('password') ? decrypt(Cookies.get('password')) : '',
      remember: Boolean(Cookies.get('rememberMe')),
    }
  },
  set(values) {
    if (values.remember) {
      Cookies.set('username', values.username, {
        expires: 30,
        secure: true,
        sameSite: 'strict',
      })
      Cookies.set('password', encrypt(values.password), {
        expires: 30,
        secure: true,
        sameSite: 'strict',
      })
      Cookies.set('rememberMe', 'true', {
        expires: 30,
        secure: true,
        sameSite: 'strict',
      })
    } else {
      ;['username', 'password', 'rememberMe'].forEach(Cookies.remove)
    }
  },
}

// 获取验证码
const refreshCaptcha = async () => {
  try {
    loading.value = true
    const response = await getCodeImg()
    captchaEnabled.value =
      response.data.captchaEnabled === undefined ? true : response.data.captchaEnabled
    if (captchaEnabled.value) {
      captchaImage.value = `data:image/gif;base64,${response.data.img}`
      captchaId.value = response.data.id
    }
  } catch (error) {
    $q.notify({
      type: 'negative',
      message: '验证码获取失败',
      position: 'top',
    })
  } finally {
    loading.value = false
  }
}

// 处理登录
const handleLogin = throttle(
  async () => {
    try {
      loading.value = true

      // 设置或清除Cookie
      cookieHandler.set(formState)

      // 调用登录
      await userStore.login({
        ...formState,
        id: captchaId.value,
      })

      // 处理重定向
      const { redirect: _, ...otherQuery } = route.query
      await router.replace({
        path: redirect.value || '/',
        query: otherQuery,
      })

      // $q.notify({
      //   type: 'positive',
      //   message: '登录成功',
      //   position: 'top',
      // })
    } catch (error) {
      // 登录失败时刷新验证码
      if (captchaEnabled.value) {
        await refreshCaptcha()
      }
    } finally {
      loading.value = false
    }
  },
  1000,
  { leading: true, trailing: false },
)

// 初始化
onMounted(async () => {
  // 从Cookie中获取记住的用户信息
  const savedCredentials = cookieHandler.get()
  Object.assign(formState, savedCredentials)

  // 获取验证码
  await refreshCaptcha()

  // 设置重定向
  redirect.value = route.query.redirect
})
</script>

<style lang="scss" scoped>
.login-page {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 24px;

  &::before {
    content: '';
    position: absolute;
    inset: 0;
    background: rgba(0, 0, 0, 0.3);
    z-index: -1;
  }
}

.login-card {
  width: 400px;
  padding: 40px;
  border-radius: 12px;
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  background-color: rgba(255, 255, 255, 0.92);

  &:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  &--mobile {
    width: 90%;
    max-width: 400px;
    padding: 24px;
  }

  &__header {
    padding: 0 0 16px;
    text-align: center;
  }

  &__body {
    padding: 0;
  }

  &__footer {
    margin-top: 24px;
    text-align: center;
    font-size: 0.875rem;
    color: #757575;
  }

  &__register-link {
    margin-left: 4px;
    font-weight: 500;
    text-decoration: none;
  }
}

.login-title {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  color: #333;
}

.login-form {
  &__input {
    margin-bottom: 12px;
    transition: all 0.3s ease;

    &:focus-within {
      transform: translateY(-1px);
    }
  }

  &__captcha {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 12px;
  }

  &__captcha-input {
    flex: 1;
  }

  &__captcha-image {
    height: 56px;
    border-radius: 4px;
    cursor: pointer;
    transition: opacity 0.2s ease;

    &:hover {
      opacity: 0.8;
    }
  }

  &__options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 16px 0;
  }

  &__forgot-password {
    font-size: 0.75rem;
    font-weight: 500;
    text-decoration: none;
  }

  &__submit {
    width: 100%;
    height: 48px;
    font-weight: 500;
    letter-spacing: 0.5px;
    text-transform: uppercase;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-1px);
    }
  }
}
</style>
